import React, { Component } from 'react';
import { Button, Modal, Radio, Progress, message, Input, Avatar } from 'antd';
import { getUrlParams } from 'yl-util';
import { api } from '../../constants';
import { fetch } from '../../utils';
import './style.scss';

let openId = '';
const urlParams = getUrlParams(window.location.href.split('?')[1]);
if (urlParams && urlParams.id) {
  openId = window.btoa(window.btoa(`${urlParams.id}yqcmxssLcJL1l8jnlC`));
}

export default class Welfare extends Component {
  state = {
    userInfo: {},
    userInfo2: {}, // index 页面用户信息
    strategyList: [],
    welfareList: [],
    welfareState: '0', // 福利状态，0 未选择，1已选择
    selectWelfareId: undefined, // 选择的福利
    assistanceList: [], // 好人榜
  }

  componentDidMount() {
    this.init();
  }

  init = async () => {
    this.getUserInfo();
    this.getStrategy();
    const response = await this.getUserCurrentWelfare();
    if (response && response.data === '0') { // 未选择福利
      this.getWelfareList();
    } else {
      this.userCurrentWelfare();
    }
  }

  // 获取规则列表
  getStrategy = async () => {
    const response = await fetch(api.getStrategy, {
      method: 'post',
      body: { openId },
    });
    if (response.msgCode === 'S0000') {
      this.setState({ strategyList: response.data });
    } else {
      message.error(response.message || '接口返回异常');
    }
  }

  // 获取福利列表
  getWelfareList = async () => {
    const response = await fetch(api.welfareList, {
      method: 'post',
      body: { openId },
    });
    // console.log('response: ', response);
    if (response.msgCode === 'S0000') {
      this.setState({ welfareList: response.data || [] });
    } else {
      message.error(response.message || '接口返回异常');
    }
  }

  // 好人榜
  assistanceList = async (payload = {}) => {
    const response = await fetch(api.assistanceList, {
      method: 'post',
      body: { openId, ...payload },
    });
    // console.log('response: ', response);
    if (response.msgCode === 'S0000') {
      this.setState({ assistanceList: response.data || [] });
    } else {
      message.error(response.message || '接口返回异常');
    }
  }

  // 展示福利列表
  showStrategy = () => {
    if (openId) {
      const { strategyList } = this.state;
      Modal.info({
        title: '玩法攻略',
        content: (
          <div>
            {strategyList.map(t => <p>{t}</p>)}
          </div>
        ),
      });
    }
  }

  // 获取用户当前福利选择内容
  getUserCurrentWelfare = async () => {
    const response = await fetch(api.getUserCurrentWelfare, {
      method: 'post',
      body: { openId },
    });
    if (response && response.msgCode === 'S0000') {
      this.setState({ welfareState: response.data });
    } else {
      message.error(response.message || '接口返回异常');
    }
    return response;
  }

  // 获取用户信息
  userCurrentWelfare = async () => {
    const response = await fetch(api.userCurrentWelfare, {
      method: 'post',
      body: { openId },
    });
    if (response && response.msgCode === 'S0000') {
      this.setState({ userInfo: response.data || {} });
      this.assistanceList({ taskId: response.data.welfareUserTaskLog.id });
    } else {
      message.error(response.message || '接口返回异常');
    }
    return response;
  }

  // 选择福利
  changeWelfare = async ({ target: { value } }) => {
    this.setState({
      selectWelfareId: value,
    });
  }

  submitWelfare = async () => {
    Modal.confirm({
      title: '确定选择该福利?',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const { selectWelfareId } = this.state;
        if (selectWelfareId) {
          const response = await fetch(api.welfareConfirm, {
            method: 'post',
            body: { openId, wcId: selectWelfareId },
          });
          if (response && response.msgCode === 'S0000') {
            this.init();
          } else {
            message.error(response.message || '接口返回异常');
          }
        } else {
          message.error('请选择福利');
        }
      },
    });
  }

  renderInitPage = () => {
    const { welfareList } = this.state;
    return (
      <div className="welfare-init-page">
        <h2>选择福利</h2>
        <Radio.Group onChange={this.changeWelfare}>
          {
            welfareList.map((item) => (
              <Radio key={item.id} value={item.id}>{item.desc}：{item.count}（需要能量{item.needPower}）</Radio>
            ))
          }
        </Radio.Group>
        <Button onClick={this.submitWelfare} type="primary">确定选择</Button>
      </div>
    );
  }

  renderWelfarePage = () => {
    const { userInfo: { welfareCfg = {}, welfareUserTaskLog = {} }, assistanceList } = this.state;
    // console.log('assistanceList: ', assistanceList);
    return (
      <div>
        <h3>收集能量拿福利</h3>
        <p>当前目标：{welfareCfg.desc} {welfareCfg.count}</p>
        <p className="display-flex">
          完成进度：{welfareUserTaskLog.hasPower}/{welfareUserTaskLog.needPower}
          <div style={{ width: 250 }}><Progress percent={window.parseInt(welfareUserTaskLog.hasPower / welfareUserTaskLog.needPower * 100)} /></div>
          <Button size="small" type="primary" disabled={welfareUserTaskLog.hasPower < welfareUserTaskLog.needPower} onClick={this.welfareReward}>领取奖励</Button>
        </p>
        <strong>好人榜</strong>
        {
          assistanceList.map(item => (
            <div>
              <img src={item.headImg} className="index-head-img" alt="" />
              {item.nickName} +{item.power} 能量
            </div>
          ))
        }
      </div>
    );
  }

  // 检查是否收集满能量
  checkPowerFull = () => {
    const { userInfo: { welfareUserTaskLog = {} } } = this.state;
    return welfareUserTaskLog.hasPower >= welfareUserTaskLog.needPower;
  }

  handleSearch = async (value) => {
    if (!value) {
      message.error('请输入id后再点击！');
      return;
    }
    const valueList = value.replace(/\s/g, '').replace(/(,|，)/g, ',').split(',');
    valueList.forEach((id, i) => {
      setTimeout(() => {
        if (!this.checkPowerFull()) {
          this.sendPower(id);
        } else {
          message.error('能量已收集满，请领取奖励后再收集');
        }
      }, 3000 * i);
    });
  }

  // 赠送能量
  sendPower = async (value) => {
    const { userInfo } = this.state;
    const response = await fetch(api.userAssistance, {
      method: 'post',
      body: { openId: window.btoa(window.btoa(`${value}yqcmxssLcJL1l8jnlC`)), taskId: userInfo.welfareUserTaskLog ? userInfo.welfareUserTaskLog.id : '' },
    });
    if (response && response.msgCode === 'S0000') {
      message.success(`${response.data.msg || '赠送成功'}: ${value}`);
      this.assistanceList({ taskId: userInfo.welfareUserTaskLog.id });
    } else {
      message.error(response.message || '接口返回异常');
    }
  }

  // 领取福利
  welfareReward = async () => {
    const { userInfo } = this.state;
    const response = await fetch(api.welfareReward, {
      method: 'post',
      body: { openId, taskId: userInfo.welfareUserTaskLog ? userInfo.welfareUserTaskLog.id : '' },
    });
    if (response && response.msgCode === 'S0000') {
      message.success(response.data || '领取成功');
      this.init();
    } else {
      message.error(response.message || '接口返回异常');
    }
  }

  // 获取用户信息
  getUserInfo = async () => {
    const params = {
      openId,
    };
    const response = await fetch(`${api.userInfo}`, {
      method: 'POST',
      body: params,
    });
    if (response.msgCode === 'S0000' && response.data) {
      this.setState({ userInfo2: response.data.user });
    }
  }

  render() {
    const { welfareState, userInfo2: userInfo } = this.state;
    return (
      <div className="page-container">
        <div className="p">个人鲜花：{userInfo.flower || 0}&nbsp;&nbsp;&nbsp;&nbsp;喇叭：{userInfo.speaker || 0} &nbsp;&nbsp;&nbsp;&nbsp;贡献：{userInfo.reduceFlower || 0}</div>
        <h1>收集能量拿福利</h1>
        <Input.Search style={{ width: 300 }} placeholder="请输入送能量ID,可用，隔开" enterButton="确定" onSearch={this.handleSearch} />
        <Button className="float-right" onClick={this.showStrategy}>查看规则</Button>
        {
          welfareState === '0' ?
            this.renderInitPage() :
            this.renderWelfarePage()
        }
      </div>
    );
  }
}
